﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.ProductionOrderAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command
{
    public class CreateProductionOrderCommand : ProductionOrderEditRequestDto,
        IRequest<Result<ProductionOrderInfoResponseDto>>
    {
    }

    public class
        CreateProductionOrderCommandHandler : IRequestHandler<CreateProductionOrderCommand,
            Result<ProductionOrderInfoResponseDto>>
    {
        private readonly IProductionOrderRepository _productionOrderRepository;
        private readonly IMapper _mapper;


        public CreateProductionOrderCommandHandler(IProductionOrderRepository productionOrderRepository,
            IMapper mapper)
        {
            _productionOrderRepository = productionOrderRepository;
            _mapper = mapper;
        }

        public async Task<Result<ProductionOrderInfoResponseDto>> Handle(CreateProductionOrderCommand request,
            CancellationToken cancellationToken)
        {
            var productionOrder = new ProductionOrder(request.Code, request.Name, request.OrderSource,
                request.OrderStatus,
                request.StandardBom.Id, request.StandardBom.Code, request.StandardBom.Name, request.Quantity,
                request.ExpectedTime, request.EndTime, request.PlanStartTime, request.PlanEndTime, request.Description);
            _productionOrderRepository.Add(productionOrder);

            await _productionOrderRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<ProductionOrderInfoResponseDto>.SuccessAsync(
                _mapper.Map<ProductionOrderInfoResponseDto>(productionOrder));
        }
    }
}